package com.rockxin.cat.base;

import android.os.Bundle;
import android.util.Log;

/**
 * <b>类名称：   </b> LazyBaseFragment <br/>
 * <b>类描述：   </b> 懒加载Fragment,当Fragment可见的时候加载数据<br/>
 * <b>创建人：   </b> leishun <br/>
 * <b>创建时间： </b> 2017/5/3 下午3:02 <br/>
 * <b>修改人：   </b><br/>
 * <b>修改时间： </b><br/>
 * <b>修改备注： </b><br/>
 *
 * @version 1.0.0 <br/>
 */
public abstract class LazyBaseFragment extends BaseFragment {
    //view是否初始化完成
    protected boolean isViewInitiated;
    //view是否可见
    protected boolean isVisibleToUser;
    //数据是否加载过
    protected boolean isDataInitiated;


    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        isViewInitiated = true;
        prepareFetchData();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        this.isVisibleToUser = isVisibleToUser;
        prepareFetchData();
    }

    //请求数据的方法
    public abstract void fetchData();

    public boolean prepareFetchData() {
        return prepareFetchData(false);
    }

    /**
     * 是否获取新数据
     *
     * @param forceUpdate 如果是True:调用fetchData()获取新数据可调用
     * @return
     */
    public boolean prepareFetchData(boolean forceUpdate) {
        if (isVisibleToUser && isViewInitiated && (!isDataInitiated || forceUpdate)) {
            fetchData();
            isDataInitiated = true;
            Log.e(getClass().getSimpleName(), "获取数据");
            return true;
        }
        return false;
    }
}
